import 'package:async/async.dart';

import 'package:boss/main.dart';
import 'package:boss/ui/page/storeEvaluate/provider/provider.dart';
import 'package:boss/ui/page/storeEvaluate/widget/bottom_keyboard_Input.dart';
import 'package:boss/ui/page/storeEvaluate/widget/item_block.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CommentList extends StatefulWidget {
  CommentList({
    Key key,
  }) : super(key: key);

  @override
  CommentListState createState() => CommentListState();
}

class CommentListState extends State<CommentList> {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  int page = 1;
  int rows = 10;

  int totalCnt = 0;

  RefreshController _refreshController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);
    Future.delayed(Duration(microseconds: 0), () async {
      getStoreCommentAverageFun();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _refreshController.dispose();
    super.dispose();
  }

  //获取门店评价详情
  getStoreCommentAverageFun() async {
    try {
      var res = await api.getStoreCommentAverageInfo();
      if (res.successful()) {
        var provider = Provider.of<StoreCommentProvider>(
          context,
          listen: false,
        );

        provider?.averageScore = res.data['averageScore'] ?? 0;
        provider?.goodCommentRate = res.data['goodCommentRate'] ?? 0;
        provider.notifyListeners();
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {}
  }

  //刷新数据
  implementUpdateData() async {
    loaderPullRefreshKey.currentState.refresh();
  }

  refresh({bool needMove = true}) async {
    await _refreshController.requestRefresh(
      needMove: needMove,
      duration: Duration(milliseconds: 100),
    );
  }

  Future<Result<List<dynamic>>> loadMoreOrderList() async {
    page += 1;

    var provider = Provider.of<StoreCommentProvider>(
      context,
      listen: false,
    );
    var res = await api.getCommentDetail(
      beginTime: provider.beginTime + ' 00:00:00',
      endTime: provider.endTime + ' 23:59:59',
      rows: rows,
      page: page,
      unionOrderId: provider.searchText ?? '',
    );
    if (res.successful()) {
      var resBean = res.data == null ? [] : res.data["items"];
      totalCnt = res.data == null ? 0 : res.data['total'];
      resBean.forEach((str) {
        provider.commentListArr.add(str);
        provider.foldStatusArr.add(false);
      });

      setState(() {});
      return Result.value(resBean);
    } else {
      return Result.value([]);
    }
  }

  Future<Result<List<dynamic>>> refreshTask() async {
    page = 1;
    var provider = Provider.of<StoreCommentProvider>(
      context,
      listen: false,
    );

    var res = await api.getCommentDetail(
      beginTime: provider.beginTime + ' 00:00:00',
      endTime: provider.endTime + ' 23:59:59',
      rows: rows,
      page: page,
      unionOrderId: provider.searchText ?? '',
    );
    if (res.successful()) {
      var resBean = res.data == null ? [] : res.data["items"];
      totalCnt = res.data == null ? 0 : res.data['total'];
      provider.commentListArr = resBean;
      provider.commentListArr.forEach((str) {
        provider.foldStatusArr.add(false);
      });

      setState(() {});
      return Result.value(resBean);
    } else {
      return Result.value([]);
    }
  }

  Future<Result<List<dynamic>>> _loadTask() async {
    return await loadMoreOrderList();
  }

  Future<Result<List<dynamic>>> _refreshTask() async {
    return await refreshTask();
  }

  //内容lsit
  Widget contentListModular() {
    return Stack(
      children: <Widget>[
        Consumer<StoreCommentProvider>(
          builder: (context, provider, _) {
            return LoaderPullRefresh<dynamic>(
                key: loaderPullRefreshKey,
                loadTask: _loadTask,
                refreshTask: _refreshTask,
                builder: (context) {
                  return ListView.builder(
                    itemBuilder: (context, index) {
                      return Container(
                        margin: EdgeInsets.only(
                          left: 24.w,
                          right: 24.w,
                          top: 12.w,
                          bottom: 26.w,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          boxShadow: [
                            BoxShadow(color: Color.fromRGBO(0, 10, 27, .05), blurRadius: 10, offset: Offset(2, 3), spreadRadius: 3.0),
                          ],
                          borderRadius: BorderRadius.circular(
                            16.w,
                          ),
                        ),
                        child: Padding(
                          padding: EdgeInsets.only(
                            left: 18.w,
                            right: 18.w,
                            top: 16.w,
                            bottom: 16.w,
                          ),
                          child: Column(
                            children: <Widget>[
                              ItemBlock(data: provider?.commentListArr[index] ?? null, provider: provider, index: index),
                              //                              Text("${provider.commentListArr[index]}"),
                              //                                Text("${provider.searchText}"),
                            ],
                          ),
                        ),
                      );
                    },
                    itemCount: totalCnt,
                  );
                });
          },
        ),
        Consumer<StoreCommentProvider>(builder: (context, provider, _) {
          return provider.replyClickIndex == null
              ? Container()
              : Positioned(
                  bottom: double.parse((provider?.keyboardHeight ?? 0).toString()),
                  child: BottomKeyboardInput(),
                );
        }),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return contentListModular();
  }
}
